<template>
  <div class="app-container-flex" v-show="showDialog && !detailInfo.visible">
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
          :filter-btn="filterInfo.searchBtn"
        >
        </new-page-filter>
        <el-button @click="closeDetailList">订单页</el-button>
      </div>
      <div class="filter-wrapper">
        <div class="display-flex">
          <new-page-filter :filter-btn="filterInfo.btnList">
            <template v-slot:filter-exportExcel>
              <el-button
                v-if="$permission('assetStoreOrder:exportExcel')"
                @click="exportDetailExcel()"
                >导出excel</el-button
              >
            </template>
          </new-page-filter>
        </div>
        <div class="display-flex">
          <Group-select
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :isGroupSearch="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :tabIndex="false"
        :pager="false"
        :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="false"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        @pageInfo="pageInfo"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>
  </div>
  <set-preference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :searchList="filterInfo.searchList"
    :fieldList="tableInfo.fieldList"
    :customizeUserVO="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
  <advanced-search
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :fieldList="tableInfo.fieldList"
    v-model:formData="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />
  <DeviceStoreOrderDetail
    v-if="detailInfo.visible"
    v-model:visible="detailInfo.visible"
    :table-row="detailInfo.data"
    @returnBack="getList"
  />
  <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
</template>
<script setup name="assetStoreOrderList">
import {
  getAssetStoreOrderDetailCustomizeListPage,
  getAssetStoreOrderDetailCustomizeList,
  getAssetStoreOrderCustomizeGroups,
  exportExcelAssetStoreOrderDetail,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDepotAll } from '@/api/core'
const DeviceStoreOrderDetail = defineAsyncComponent(() => import('./detail'))

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible'])

// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      depotAuth: {
        asTbName: 'asset_store_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [{ value: 'exportExcel', type: 'slot' }],
})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
const productionDateTime = ref([])
const validityDateTime = ref([])
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  data: {},
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
      show: false,
    },
    receiveNo: {
      label: '收货单号',
      value: 'receiveNo',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('assetStoreOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_store_order_status',
      show: false,
      hidden: true,
    },
    typeValue: {
      label: '状态',
      value: 'typeValue',
      asValue: 'type',
      componentType: 'select-model',
      code: 'other_store_type',
      show: false,
      hidden: true,
    },
    depotName: {
      label: '出库仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  getCustomize()
}
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: exportExcelAssetStoreOrderDetail, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportDetailExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
/* function exportDetailExcel() {
  exportExcelAssetStoreOrderDetail(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
} */
function closeDetailList() {
  proxy.$store.dispatch('app/toggleOpenFilter')
  showDialog.value = false
  emits('callback')
}
function showDetail(row) {
  row.id = row.orderId
  detailInfo.value.data = row
  detailInfo.value.visible = true
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  //点击分组
  if (arr.length) {
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    proxy.$message.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getAssetStoreOrderCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getAssetStoreOrderDetailCustomizeList(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'assetStoreOrder',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  if ((await groupSelectInfo.value.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetStoreOrderDetailList-com.slip.spd.entity.vo.device.store.AssetStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getAssetStoreOrderDetailCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}
</script>

<style scoped></style>
